<script>
(function($) {
    $(window).load(function() {
        var counterbab = 1;
		var judulval = false;
		var catval = false;
		var tagval = false;
		var sinopsisval = false;
		var MinJudul = 5; 
		var MinSinopsis = 100; 
		var isibabval = false;
		var judulbabval = false;
		var MinJudulBab = 5; 
		var MinIsiBab = 200;
 
		var PlaceHolderJudulBab = "Isi judul bab";
		var PlaceHolderIsiBab = "Silakan salin dan tempel atau ketik isi bab Anda di sini, jika judul tidak diisi dan isi bab kosong, maka bab ini tidak akan tersimpan.";
		var MsgJudul = "Judul harus diisi minimal "+MinJudul+" karakter!";
		var MsgKategori ="Pilih satu kategori! Anda TIDAK DAPAT mengubah kategori apabila cerita sudah ditayangkan!";
		var MsgTag = 'Tag wajib diisi, pisahkan tag dengan tanda ","! Anda TIDAK DAPAT mengubah tag apabila cerita sudah ditayangkan.';
		var MsgSinopsis = "Sinopsis wajib diisi minimal "+MinSinopsis+" karakter!";
		var MsgIsiBab = "Wajib isi bab minimal "+MinIsiBab+" karakter!";
		var MsgJudulBab = "Judul bab harus diisi minimal "+MinJudulBab+" karakter!";
		
        $("#lastmodifiedscroll").mCustomScrollbar();
        $("#pilihaneditorscroll").mCustomScrollbar();
        $('#dialog-editsampul').dialog({
            modal: true,
            autoOpen: false,
            title: 'Edit Sampul',
            width: 300,
            height: 300,
            position: ['middle', 40]

        });
        $('[id*=EditSampul]').click(function(e) {
            e.preventDefault();
            var openpage = $(this).attr("href");
            $("#dialog-editsampul").css('display', 'block');
            $("#dialog-editsampul").load(openpage);
            $('#dialog-editsampul').dialog('open');
        });

        $('#dialog-hapusbab').dialog({
            modal: true,
            autoOpen: false,
            title: 'Konfirmasi Hapus Bab',
            width: 500,
            height: 200,
            position: ['middle', 60],
            buttons: {
                "Ya": function() {
                    $("#hapusbabok").click();
                },
                "Batal": function() {
                    $(this).dialog("close");
                }
            }

        });
        $('[id*=HapusBab]').click(function(e) {
            e.preventDefault();
            var ids = $(this).attr("href");
            var items = ids.split("|");
            $("#hiddenbabid").val(items[0]);
            $("#hiddenbookid").val(items[1]);
            $("#dialog-hapusbab").css('display', 'block');
            $('#dialog-hapusbab').dialog('open');
        });

        $(".up,.down").click(function() {
            var row = $(this).parents("tr:first");
            if ($(this).is(".up")) {
                row.insertBefore(row.prev());
            } else {
                row.insertAfter(row.next());
            }
        });
		// untuk halaman kelola cerita ****
        function DoAction(){
		var idbab = new Array();
            var idbablongstring = "";

            $("#tablebab").find("tr").each(function() {
                var row = $('[id*=linkbab]').closest($(this));
                var idbabhref = $('[id*=linkbab]', row).attr("href");
                idbab.push(idbabhref);
            });
            for (var i = 0; i < idbab.length; i++) {
                var id = idbab[i];
                if (i == idbab.length - 1) {
                    idbablongstring += id;
                } else {
                    idbablongstring += id + "|";
                }
            };
			$("#idbabnew").val(idbablongstring);
		};
		DoSave = function() {
            DoAction();
            $("#simpanpostok").click();
        };
		DoSaveandPublish = function() {
			DoAction();
            $("#tayangkanpostok").click();
        };
		// ****
        $('#dialog-hapusbuku').dialog({
            modal: true,
            autoOpen: false,
            title: 'Konfirmasi Hapus Cerita',
            width: 500,
            height: 200,
            position: ['middle', 170],
            buttons: {
                "Ya": function() {
                    $("#hapusbukuok").click();
                },
                "Batal": function() {
                    $(this).dialog("close");
                }
            }

        });
        $('[id*=HapusBuku]').click(function(e) {
            e.preventDefault();
            var id = $(this).attr("href");
            $("#hiddenbookid2").val(id);
            $("#dialog-hapusbuku").css('display', 'block');
            $('#dialog-hapusbuku').dialog('open');
        });
        if ($('.paragrafcerita').height() < 2692) {
            $('.controls').css('display', 'none');
        } else {
            $('.controls').css('display', 'block');
        }

        DoAddBab =
        function() {
                var ul = $('#tabtable').find("ul");
                var divTabs = $('#tab-content');
                $('#tabtable').find("li").each(function() {
                    $(this).removeAttr("class");
                });
                $('#tab-content').find("div").each(function() {
                    $(this).removeClass("tab-pane active").addClass("tab-pane");
                });
                var tabcontent = "<li class='active'><span ><a href='#pane" + (counterbab) + "' data-toggle='tab'>Bab " + (counterbab) + "</a>&nbsp;&nbsp; <a id='"+counterbab+"' class='remove'>x</a>&nbsp;&nbsp;</span></li>";
                var tabDiv = " <div id='pane" + (counterbab) + "' class='tab-pane active'><br/><input class='form-control tinggitextbox' id='title" + (counterbab) + "' type='text' name='title" + (counterbab) + "' placeholder='"+PlaceHolderJudulBab+"' ></input><br/><textarea class='kotaktext' name='description" + (counterbab) + "' id='description" + (counterbab) + "' placeholder='"+PlaceHolderIsiBab+"'></textarea> </div>";
                ul.append(tabcontent);
                divTabs.append(tabDiv);
                counterbab++;
				$('#tabtable').tabs("refresh");
        };
	// halaman profilku.php ****
	ShowEdit = 
	function (id){
	  var idtext = $(id).attr('id');
		$('#'+idtext+'edit').css('display','block');
		$('#'+idtext+'div').css('display','none');
		if (idtext=='jk'){
		$('#rdgroup').find('input[type=radio]').each(function(){
			var value = $(this).val();
			if ($('#lbjk').text()==value){
				$(this).attr('checked',true);
				};
			});
		};
	};
	HideEdit = 
	function (id){
	  var idtext = $(id).attr('id');
		$('#'+idtext+'edit').css('display','none');
		$('#'+idtext+'div').css('display','block');
	};
	SaveEdit = 
	function(id){
		var idtext = $(id).attr('id');
		switch (idtext){
			case 'namalengkap' :
				var fname = $('#txtfirstname').val();
				var lname = $('#txtlastname').val();
				$('#lb'+idtext).text(fname + ' ' + lname);
				$('#fnameeditok').val(fname);
				$('#lnameeditok').val(lname);
				HideEdit(id);
			break;
			case 'bio':
				$('#lb'+idtext).text($('#ta'+idtext).val());
				$('#'+idtext+'editok').val($('#ta'+idtext).val());
				HideEdit(id);
			break;
			case 'website': 
				var websitetext =	$('#a'+idtext).text($('#txt'+idtext).val());
				$('#'+idtext+'editok').val(websitetext);
				HideEdit(id);
			break;
			case 'TTL' : 
				var tempatlahir = $('#txttempatlahir').val();
				var tgllahir = $('#txttgllahir').val();
				$('#lb'+idtext).text(tempatlahir + " / " + tgllahir);
				$('#tempatlahireditok').val(tempatlahir);
				$('#tgllahireditok').val(tgllahir);
				HideEdit(id);
			break;
			case 'jk' : 
				var check = "";
				var ischecked = false;
				$('#rdgroup').find('input[type=radio]').each(function(){
				if ($(this).attr("checked")=='checked'){
					checkedval = $(this).val();
					$('#'+idtext+'editok').val(checkedval);
					ischecked = true;
					}
				});
				if (ischecked==true){
					$('#lb'+idtext).text(checkedval);
					HideEdit(id);	}
				else {alert('Pilih jenis kelamin dulu!');}
			break;
			case 'pekerjaan' : 
				var pekerjaantext = $('#txt'+idtext).val()
				$('#lb'+idtext).text(pekerjaantext);
				$('#'+idtext+'editok').val(pekerjaantext);
				HideEdit(id);
			break;
			case 'notelp': 
				var notelptext=	$('#txt'+idtext).val();
				$('#lb'+idtext).text(notelptext);
				$('#'+idtext+'editok').val(notelptext);
				HideEdit(id);
			break;
			case 'email' : 
				var emailtext = $('#txt'+idtext).val();
				$('#lb'+idtext).text(emailtext);
				$('#'+idtext+'editok').val(emailtext);
				HideEdit(id);
			break;
			//case 'password':
			//	var cekpassword = false;
			//	if (cekpassword==false){
			//		$('#error'+idtext).text('Password lama tidak sesuai! Harap masukkan password lama dengan benar!');
			//	}
			//break;
		}
	};
	$("input[type='checkbox']")
	$("input[type='radio']").click(function()
	{
	  var previousValue = $(this).attr('previousValue');
	  var name = $(this).attr('name');

	  if (previousValue == 'checked')
	  {
		$(this).removeAttr('checked');
		$(this).attr('previousValue', false);
	  }
	  else
	  {
		$("input[name="+name+"]:radio").attr('previousValue', false);
		$(this).attr('previousValue', 'checked');
	  }
	});
	
	
	// ****
	$(document).on('keyup',"#descriptionbab", function(){
		var currentString = $.trim($("#descriptionbab").val());
		if (currentString.length < MinIsiBab )  {  /*or whatever your number is*/
			$('#errorisibab').text(MsgIsiBab);
			$(this).css('border','2px solid red');
			isibabval=false;
		} else {
			isibabval = true;
			$(this).css('border','2px solid green');
			$('#errorisibab').text('');
		}
	});

	$(document).on('keyup',"#titlebab", function(){
		var currentString = $.trim($("#titlebab").val());
		if (currentString.length < MinJudulBab )  {  /*or whatever your number is*/
			   $('#errorjudulbab').text(MsgJudulBab);
			  $(this).css('border','2px solid red');
			  judulbabval = false;
		} else {
			 judulbabval = true;
			  $(this).css('border','2px solid green');
			  $('#errorjudulbab').text('');
		}
	}); 

	DoValidationPostBab = 
		function(){
			if (judulbabval==false){
			 $('#errorjudulbab').text(MsgJudulBab);
				}
			if (isibabval == false){
			$('#errorisibab').text(MsgIsiBab);
			}
			if (judulbabval==true && isibabval==true){
				return true;
			}
			else {
				return false;
			}
		};	
	$("#DoPublishBab").on("click", function(){
		if (DoValidationPostBab()==true){
			$('#publishbab').click();
		}
	});
 
	$("#DoDraftBab").on("click", function(){
		if (DoValidationPostBab()==true){
			$('#draftbab').click();
		};
	});

	$('#tabtable a.remove').live('click', function() {
		var ID = $(this).attr("ID");
	
			// remove content tab and related content
		var tabid = $('#pane'+ ID).remove();
			
			//remove li
		$(this).parent().remove();
	});
		
    function publishordraftbuku() {
        var tab = new Array();
            //var tab2 = new Array();
        var tabstring = "";
            //var tabjudulstring = "";
            //$("#tabtable").find("text").each(function() {
              //  var idtext = $(this).attr("id");
                //tab2.push(idtext);
            //});
			
        $("#tabtable").find("textarea").each(function() {
			// do minor validation in textaera		
			var idtextarea = $(this).attr("id");
			if ($.trim($(this).val()).length > 0){
                    tab.push(idtextarea);
				}
			else {
					if ($.trim($(this).prev().prev().val()).length>0) //br/input// jangan ditambah tag lain di postbab.php
					{
					tab.push(idtextarea);
					}	
				;}
        });
        for (var i = 0; i < tab.length; i++) {
            var id = tab[i];
            if (i == tab.length - 1) {
                    tabstring += id;
            } else {
                    tabstring += id + "|";
            }
        };
           // for (var i = 0; i < tab2.length; i++) {
             //   var id2 = tab2[i];
               // if (i == tab2.length - 1) {
                 //   tabjudulstring += id2;
                //} else {
                  //  tabjudulstring += id2 + "|";
                //}
            //};
         $('#hidallbabtab').val(tabstring);
            //$('#hidallbabtabjudul').val(tabjudulstring);
        };
		
		$('#title0').on('keyup', function(event) {
			var currentString = $.trim($("#title0").val());
			if (currentString.length < MinJudul )  {  /*or whatever your number is*/
			  $('#errorjudulbuku').text(MsgJudul);
			 //  $('#errorjudulbab').text(MsgJudul);
			  $(this).css('border','2px solid red');
			  judulval = false;
		} else {
			 judulval = true;
			  $(this).css('border','2px solid green');
			 $('#errorjudulbuku').text('');
			 // $('#errorjudulbab').text('');
			}
		});
		
		$('#description0').on('keyup', function(event) {
			var currentString = $.trim($("#description0").val());
			if (currentString.length < MinSinopsis )  {  /*or whatever your number is*/
			  $('#errorsinopsisbuku').text(MsgSinopsis);
			   // $('#errorisibab').text(MsgIsiBab);
			  $(this).css('border','2px solid red');
			  sinopsisval = false;
			  //isibabval=false;
			} else {
			 sinopsisval = true;
			 //isibabval = true;
		    $(this).css('border','2px solid green');
			$('#errorsinopsisbuku').text('');
			  //$('#errorisibab').text('');
			}
		});
		
		
		//for wp_dropdowncategories
		var dropdown = document.getElementById("cat");
		function onCatChange() {
			if ( dropdown.options[dropdown.selectedIndex].value < 0 ) {
				$('#errorkatbuku').text(MsgKategori);
				catval = false;
			}
			else {
				catval = true;
				$('#errorkatbuku').text('');}
		};
		dropdown.onchange = onCatChange;
	//*****************
		$('#post_tags').on('keyup',function(event){
		if ($.trim($('#post_tags').val()).length < 1){
			 $('#errortagbuku').text(MsgTag);
			  tagval = false;
		}
		 else {
		  $('#errortagbuku').text('');
		  tagval = true;
		}
		});
		
		DoValidationTulisCerita = 
		function(){
			if (judulval==false){
			 $('#errorjudulbuku').text(MsgJudul);
				}
			if (catval == false){
			 $('#errorkatbuku').text(MsgKategori);
				}
			if (tagval == false){
				$('#errortagbuku').text(MsgTag);
			}
			if (sinopsisval == false){
				$('#errorsinopsisbuku').text(MsgSinopsis);
			}
			if (judulval==true && catval == true && tagval == true && sinopsisval==true)	{
				return true;
			}
			else {
				return false;
			}
		};
		
		DoDraftBuku =
		function(){
			if (DoValidationTulisCerita()==true){
				publishordraftbuku();
				$('#draftbuku').click();
			}
		};
		
		DoPublishBuku =
			function(){
			if (DoValidationTulisCerita()==true){
				publishordraftbuku();
				$('#publishbuku').click();
			}
		};
				
    });
})(jQuery);
</script>
